package com.ruoyi.stock.controller;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.stock.domain.StockInventory;
import com.ruoyi.stock.service.IStockInventoryService;
import com.ruoyi.basedata.domain.BaseProduct;
import com.ruoyi.basedata.service.IBaseProductService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 库存信息Controller
 * 
 * @author ruoyi
 * @date 2025-06-17
 */
@Controller
@RequestMapping("/stock/inventory")
public class StockInventoryController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(StockInventoryController.class);

    private String prefix = "stock/inventory";

    @Autowired
    private IStockInventoryService stockInventoryService;
    
    @Autowired
    private IBaseProductService baseProductService;

    @RequiresPermissions("stock:inventory:view")
    @GetMapping()
    public String inventory()
    {
        return prefix + "/inventory";
    }

    /**
     * 查询库存信息列表
     */
    @RequiresPermissions("stock:inventory:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StockInventory stockInventory)
    {
        startPage();
        List<StockInventory> list = stockInventoryService.selectStockInventoryList(stockInventory);
        return getDataTable(list);
    }

    /**
     * 导出库存信息列表
     */
    @RequiresPermissions("stock:inventory:export")
    @Log(title = "库存信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(StockInventory stockInventory)
    {
        List<StockInventory> list = stockInventoryService.selectStockInventoryList(stockInventory);
        ExcelUtil<StockInventory> util = new ExcelUtil<StockInventory>(StockInventory.class);
        return util.exportExcel(list, "库存信息数据");
    }

    /**
     * 新增库存信息
     */
    @RequiresPermissions("stock:inventory:add")
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存库存信息
     */
    @RequiresPermissions("stock:inventory:add")
    @Log(title = "库存信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(StockInventory stockInventory)
    {
        return toAjax(stockInventoryService.insertStockInventory(stockInventory));
    }

    /**
     * 修改库存信息
     */
    @RequiresPermissions("stock:inventory:edit")
    @GetMapping("/edit/{inventoryId}")
    public String edit(@PathVariable("inventoryId") Long inventoryId, ModelMap mmap)
    {
        StockInventory stockInventory = stockInventoryService.selectStockInventoryByInventoryId(inventoryId);
        
        // 检查商品名称是否为空，如果为空则从基础数据中获取
        if (stockInventory.getProductName() == null || stockInventory.getProductName().isEmpty()) {
            Long productId = stockInventory.getProductId();
            if (productId != null) {
                try {
                    // 从基础数据模块获取商品信息
                    BaseProduct baseProduct = baseProductService.selectBaseProductByProductId(productId);
                    if (baseProduct != null && baseProduct.getProductName() != null) {
                        stockInventory.setProductName(baseProduct.getProductName());
                        // 更新库存信息中的商品名称
                        stockInventoryService.updateStockInventory(stockInventory);
                        log.info("Updated product name for inventory ID: {}, product ID: {}, name: {}", 
                                inventoryId, productId, baseProduct.getProductName());
                    } else {
                        log.warn("Product not found in base data for product ID: {}", productId);
                        stockInventory.setProductName("商品" + productId);  // 设置默认名称
                    }
                } catch (Exception e) {
                    log.error("Error getting product name from base data", e);
                    stockInventory.setProductName("商品" + productId);  // 设置默认名称
                }
            }
        }
        
        mmap.put("stockInventory", stockInventory);
        return prefix + "/edit";
    }

    /**
     * 修改保存库存信息
     */
    @RequiresPermissions("stock:inventory:edit")
    @Log(title = "库存信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(StockInventory stockInventory)
    {
        return toAjax(stockInventoryService.updateStockInventory(stockInventory));
    }

    /**
     * 删除库存信息
     */
    @RequiresPermissions("stock:inventory:remove")
    @Log(title = "库存信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(stockInventoryService.deleteStockInventoryByInventoryIds(ids));
    }

    /**
     * 根据商品ID获取商品名称
     */
    @GetMapping("/getProductName/{productId}")
    @ResponseBody
    public AjaxResult getProductName(@PathVariable("productId") Long productId)
    {
        if (productId == null) {
            return AjaxResult.error("商品ID不能为空");
        }
        
        try {
            // 从基础数据模块获取商品信息
            BaseProduct baseProduct = baseProductService.selectBaseProductByProductId(productId);
            if (baseProduct != null && baseProduct.getProductName() != null) {
                return AjaxResult.success("获取成功", baseProduct.getProductName());
            } else {
                return AjaxResult.error("未找到对应的商品");
            }
        } catch (Exception e) {
            log.error("获取商品名称时发生错误", e);
            return AjaxResult.error("获取商品名称失败");
        }
    }
}
